// 安装vue-amap: npm i vue-amap
<template>
  <div>
      position: [{{ lng }}, {{ lat }}] address: {{ address }}
      <el-row>
        <el-col span="12">
          <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box>
        </el-col>
      </el-row>
      <el-row style="height: 500px">
        <el-amap
          vid="amapDemo"  
          :center="center"
          :zoom="zoom"  
          class="amap-demo"
          :events="events">
        </el-amap>
        <div class="toolbar">
          position: [{{ lng }}, {{ lat }}] address: {{ address }}
        </div>
      </el-row>
  </div>
</template>

<script>
  import VueAMap from 'vue-amap'
  let amapManager = new VueAMap.AMapManager()
  export default {
    name: 'fence-manage',
    data () {
      let self = this;
      return {
        amapManager,
        zoom: 13,
        center: [106.5572085, 29.6154994],
        address: '', // 地址
        lng: 0, // 维度
        lat: 0, // 经度
        searchOption: {
          city: '',
          citylimit: false
        },
        events: {
          click(e) {
            let { lng, lat } = e.lnglat;
            self.lng = lng;
            self.lat = lat;
            // 这里通过高德 SDK 完成。
            var geocoder = new AMap.Geocoder({
              radius: 1000,
              extensions: "all"
            });        
            geocoder.getAddress([lng ,lat], function(status, result) {
              if (status === 'complete' && result.info === 'OK') {
                if (result && result.regeocode) {
                  self.address = result.regeocode.formattedAddress;
                  self.$nextTick();
                }
              }
            });        
          }
        }
      }
    },
    methods: {
      // 搜索
      onSearchResult (pois) {
        let latSum = 0
        let lngSum = 0
        if (pois.length > 0) {
          pois.forEach(poi => {
            let { lng, lat } = poi
            lngSum += lng
            latSum += lat
          })
          let center = {
            lng: lngSum / pois.length,
            lat: latSum / pois.length
          }
          this.center = [center.lng, center.lat]
          this.zoom = 15
        }
      }
    }
  }
</script>

<style>
  .amap-box {
    height: 500px;
  }

</style>

